# ------------------------------------------------------------------------------
# Autor:             terrasky
# Date:              2024-05-31
# Ver:               v1.0 定义文件标签【】   
# ------------------------------------------------------------------------------
# _*_ coding:UTF-8 _*_

import sys,re,os,csv
import shutil #用于移动文件
import random #用于随机选取
import tkinter as tk
import sqlite3
from pypinyin import lazy_pinyin,Style

DBPATH = "tagdb.db"

class QApplication():
    def __init__(self):
        self.conn = sqlite3.connect(DBPATH)
        self.cursor = self.conn.cursor()
        self.root = tk.Tk()
        self.var = tk.StringVar()
        self.lis = []   # 关联self.listb (item,hothit)

        self.entry = tk.Entry(self.root,textvariable=self.var)
        self.listb = tk.Listbox(self.root)
        self.label = tk.Label(self.root, text="")

        self.entry.bind('<Return>',self.entry_return)
        self.listb.bind('<Key>',self.listb_keypress)
        self.listb.bind('<Double-Button-1>',self.change_name)
        self.var.trace("w",self.update_content)

        self.entry.pack()
        self.listb.pack()
        self.label.pack()

        self.update_lis()
        self.update_listb(self.lis)

    def change_name(self,event):
        selected_item = self.listb.get(self.listb.curselection())
        for path in sys.argv[1:]:
            basename=os.path.basename(path)
            dirname=os.path.dirname(path)
            basename = "【"+selected_item+"】"+basename
            newfilename = os.path.join(dirname,basename)
            try:
                os.rename(path,newfilename)
            except:
                self.label['text']='重命名error'
                return 

            try:
                self.cursor.execute("update tag set hothit=hothit+1 where name=?",(selected_item,))
                self.conn.commit()
                self.label['text']='ok'
            except:
                self.label['text']='数据读取error'
                return 

            sys.exit()


    def run(self):
        self.root.mainloop()


    def listb_keypress(self,event):
        if event.keysym == 'BackSpace':
            self.entry.delete(len(self.var.get())-1,'end')
        elif event.keysym == 'Delete':
            self.entry.delete(0,1)
        else:
            self.entry.insert('end',event.char)


    def update_content(self,*args):
        text =self.var.get()
        # 过滤得到新显示列表
        lis=  list(filter(lambda s: (''.join(lazy_pinyin(s[0],style=Style.FIRST_LETTER))).find(text)!=-1 
            or s[0].find(text)!=-1,self.lis))
        self.update_listb(lis)


    def entry_return(self,event):
        text = event.widget.get()
        event.widget.delete(0, "end")
        if not text:
            return

        if text not in [item for item,_ in self.lis]:
            self.lis.append((text,0))
            self.cursor.execute("insert into tag(name) VALUES (?)",(text,))
            self.conn.commit()
            self.update_listb(self.lis)
        else:
            print("已经在列表内")


    def update_listb(self,lis):
        self.listb.delete(0,'end')

        lis.sort(key=lambda elem:elem[1],reverse=True)
        for index,cu in enumerate(lis):
            self.listb.insert(index,cu[0])


    def update_lis(self):
        self.cursor.execute("SELECT name,hothit from tag")
        self.lis = self.cursor.fetchall()


if __name__ == '__main__':
    print(sys.argv)
    app = QApplication()
    app.run()
    sys.exit()
    
    